package com.tianji.aigc.memory.mongoda;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tianji.aigc.memory.MessageUtil;
import com.tianji.aigc.memory.MyChatMemoryRepository;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 基于MongoDB 实现 ChatMemoryRepository
 */
public class MongoDBChatMemoryRepository implements ChatMemoryRepository , MyChatMemoryRepository {

    @Resource
    private MongoTemplate mongoTemplate;

    //返回所有conversationId
    @Override
    public List<String> findConversationIds() {

        List<ChatRecord> chatRecords = this.mongoTemplate.findAll(ChatRecord.class);
        return CollStreamUtil.toList(chatRecords,ChatRecord::getConversationId);
    }

    @Override
    public List<Message> findByConversationId(String conversationId) {

        Query query = Query.query(Criteria.where("conversationId").is(conversationId));
        var chatRecord = this.mongoTemplate.findOne(query, ChatRecord.class); //找一个
        if (null==chatRecord){
            return List.of();
        }
        return CollStreamUtil.toList(chatRecord.getMessages(),MessageUtil::toMessage);
    }

    @Override
    public void saveAll(String conversationId, List<Message> messages) {
      /*  // 先删除原有数据
        this.deleteByConversationId(conversationId);

        // 构造 chatRecord 数据
        var chatRecord = ChatRecord.builder()
                .conversationId(conversationId)
                .messages(CollStreamUtil.toList(messages, MessageUtil::toJson))
                .build();

        // 保存到MongoDB中
        this.mongoTemplate.save(chatRecord);*/

        //删除原有数据
        this.deleteByConversationId(conversationId);

        //创建chatRecord数据
        var chatRecord =ChatRecord.builder()
                .conversationId(conversationId)
                .messages(CollStreamUtil.toList(messages,MessageUtil::toJson)) //将传进来的message对象列表转换为Json字符串数据
                .build();
        //保存数据到MongoDB
        this.mongoTemplate.save(chatRecord);
    }

    @Override
    public void deleteByConversationId(String conversationId) {

        Query query = Query.query(Criteria.where("conversationId").is(conversationId)); //构造条件
        this.mongoTemplate.remove(query,ChatRecord.class);  //执行语句
    }

    @Override
    public void optimization(String conversationId) {
        //TODO 待完成
    }
}
